// pages/match-history/match-history.js
import { matchApi } from '../../services/api';

Page({
  data: {
    historyList: [],
    loading: false,
    page: 1,
    pageSize: 10,
    hasMore: true
  },

  onLoad() {
    this.loadHistoryList();
  },

  onPullDownRefresh() {
    this.setData({
      page: 1,
      historyList: [],
      hasMore: true
    });
    this.loadHistoryList().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadHistoryList();
    }
  },

  async loadHistoryList() {
    if (this.data.loading) return;

    try {
      this.setData({ loading: true });

      const { list, total } = await matchApi.getHistory({
        page: this.data.page,
        pageSize: this.data.pageSize
      });

      const processedList = list.map(item => ({
        ...item,
        createTime: this.formatTime(item.createTime)
      }));

      this.setData({
        historyList: [...this.data.historyList, ...processedList],
        page: this.data.page + 1,
        hasMore: this.data.historyList.length + list.length < total
      });

    } catch (err) {
      console.error('获取匹配历史失败', err);
      wx.showToast({
        title: err.message || '获取历史失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  formatTime(timeStr) {
    if (!timeStr) return '';
    const date = new Date(timeStr);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');
    const second = date.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  },

  handleViewDetail(e) {
    const { matchId } = e.currentTarget.dataset;
    const matchInfo = this.data.historyList.find(item => item.matchId === matchId);
    
    const matchInfoStr = encodeURIComponent(JSON.stringify(matchInfo));
    wx.navigateTo({
      url: `/pages/match-result/match-result?matchInfo=${matchInfoStr}`
    });
  }
});